using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Code_Generator
{
	static class HelperMethods
	{
		public static void Replace(this StringBuilder target, string pattern, IList<string> values)
		{
			target.Replace(pattern, string.Join("\r\n", values));
		}

		public static void Replace(this StringBuilder target, string pattern, object value)
		{
			if (value == null || value == DBNull.Value)
				target.Replace(pattern, "");
			else
				target.Replace(pattern, value.ToString());
		}

		public static void ReplaceEncoded(this StringBuilder target, string pattern, object value)
		{
			if (value == null || value == DBNull.Value)
				target.Replace(pattern, "");
			else
				target.Replace(pattern, value.ToString().Replace("\"", "\"\""));
		}

		public static void ReplaceClrAlias(this StringBuilder target, string pattern, object value)
		{
			if (value == null || value == DBNull.Value)
				target.Replace(pattern, "");
			else
				target.Replace(pattern, value.ToString().ToClrName());
		}

		//public static void ReplaceIdentifier(this StringBuilder target, string pattern, object value)
		//{
		//	if (value == null || value == DBNull.Value)
		//		target.Replace(pattern, "");
		//	else
		//	{
		//		var line = value.ToString();
		//		IEnumerable<string> words = line.Split(' ', '\t', '-');
		//		words = words.Where(w => w != "").Select(w => w.Substring(0, 1).ToUpperInvariant() + w.Substring(1));
		//		var result = string.Join("", words);

		//		target.Replace(pattern, result);
		//	}
		//}

		public static void ReplaceEncoded(this StringBuilder target, string pattern, string value)
		{
			target.Replace(pattern, value.Replace("\"", "\"\""));
		}

		public static string F(this string format, params  object[] args)
		{
			return String.Format(format, args);
		}

		static readonly char[] InvalidCharacters = new char[] { ' ', '.', ',', '$' };

		public static string ToClrName(this string value)
		{
			string temp = value;
			foreach (char c in InvalidCharacters)
			{
				temp = temp.Replace(c.ToString(), "");
			}

			if (!Char.IsLetter(temp[0]) && temp[0] != '_')
				temp = "_" + temp;

			return temp;
		}
	}
}
